import os

if os.name == 'posix':
    import pyudev

    def scan_xense_devices():
        """
        Scan for Xense devices connected to the system.

        Returns:
        - dict: A dictionary mapping serial numbers to device IDs
        """
        # Create a context object to interact with udev
        context = pyudev.Context()
        xense_devices = {}

        # 查找所有video4linux设备
        for device in context.list_devices(subsystem='video4linux'):
            vendor_id = device.get('ID_VENDOR_ID')
            product_id = device.get('ID_MODEL_ID')
            serial_number = device.get('ID_MODEL')
            cam_id = int(device.device_node.split('video')[-1])

            if vendor_id=="a000" and product_id=="b111":
                # 每个USB相机设备通常会创建两个video设备节点, 一个用于视频流 (MJPEG/YUYV等格式), 一个用于元数据或其他功能
                # 例如 /dev/video0 和 /dev/video1 可能同属于同一个相机设备, 使用这个相机时，通常应该使用编号较小的设备节点
                if xense_devices.get(serial_number) is None or cam_id < xense_devices[serial_number]:
                    xense_devices[serial_number] = cam_id

        print(f"Found Xense devices: {xense_devices}")
        return xense_devices


elif os.name == 'nt':
    import wmi
    import ctypes

    # Initialize the WMI client
    wmi_clent = wmi.WMI()

    # 加载对应位数动态链接库
    _CvCameraIndex = ctypes.cdll.LoadLibrary(r'lib\CvCameraIndex.dll')
    _CvCameraIndex.getCameraIndex.argtypes = [ctypes.c_char_p]
    _CvCameraIndex.getCameraIndex.restype = ctypes.c_int

    def get_camera_id(hwid: str) -> int:
        """
        获取cv.VideoCapture(camera_index, cv2.CAP_DSHOW)参数camera_index

        Parameters:
        - hwid : str, 硬件标识, 不区分大小写, 如 vid_1234&pid_4321, 或 op000001

        Returns:
        - int, camera_index
        """
        return _CvCameraIndex.getCameraIndex(bytes(hwid, encoding='utf-8'))

    def scan_xense_devices():
        """
        Scan for Xense devices connected to the system.

        Returns:
        - dict: A dictionary mapping serial numbers to device IDs
        """
        devices_ids = wmi_clent.query(f"SELECT * FROM Win32_USBHub WHERE DeviceID LIKE '%VID_A000&PID_B111%'")
        devices_ids = [dev.DeviceID.split('\\')[-1] for dev in devices_ids]
        
        devices_map = { dev: get_camera_id(dev) for dev in devices_ids }
        print(f"Found Xense devices: {devices_map}")

        return devices_map
        

if __name__ == '__main__':
    import cv2
    from ezgl.utils.QtTools import qtcv

    devices = scan_xense_devices()

    # 按次序读取 Xense 设备
    for serial_number, cam_id in devices.items():
        cap = cv2.VideoCapture(cam_id)

        while True:
            ret, frame = cap.read()
            if not ret:
                break
            qtcv.imshow(f"Xense {serial_number}", frame)

            if qtcv.waitKey(10) == qtcv.Key.Key_Escape:
                break
